package com.baseandroid.push;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.baseandroid.MyApplication;
import com.baseandroid.baidutts.BaiduTts;
import com.baseandroid.baidutts.BaiduTtsEvent;
import com.baseandroid.baidutts.UiMessageListener;
import com.baseandroid.config.Global;
import com.baseandroid.retrofit.RxObserver;
import com.baseandroid.retrofit.json.Data;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class PushDoneService extends Service {

    private boolean needPlayVoice;
    private int mStreamVolume;
    private AudioManager mAudioManager;

    @Override
    public void onCreate() {
        super.onCreate();
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        /*--百度语音初始化--*/
        BaiduTts.getInstance().initialTts(mainHandler);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            mStreamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            String msg = intent.getStringExtra("msg");
            String isvoice = intent.getStringExtra("isvoice");
            needPlayVoice = Global.getPushVoiceState();
            needPlayVoice &= TextUtils.equals(isvoice, "1");
            if (needPlayVoice) {
                speak(msg, intent.getStringExtra("msgpushid"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            String msgpushts = intent.getStringExtra("msgpushts");
            String msgpushid = intent.getStringExtra("msgpushid");
            String localmills = intent.getStringExtra("localmills");
            String msgpushch = intent.getStringExtra("msgpushch");
            String orderts = intent.getStringExtra("orderts");
            if (!TextUtils.isEmpty(msgpushts)) {
                postJpushDelayed(msgpushts, msgpushid, localmills, msgpushch, orderts);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /*--极光推送延迟统计--*/
    private void postJpushDelayed(String msgpushts, String msgpushid, String localmills, String msgpushch, String orderts) {
        MyApplication.getMyAppComponent()
                .retrofitMyApiHelper()
                .pushReportData(getJpushDelayEventsObject(msgpushts, msgpushid, localmills, msgpushch, orderts))
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxObserver<Data>() {
                    @Override
                    public void onNext(Data data) {
                        super.onNext(data);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    private BuriedEventPacket getJpushDelayEventsObject(String msgpushts, String msgpushid, String localmills, String msgpushch, String orderts) {
        BuriedEventPacket packet = new BuriedEventPacket();
        BuriedEvent event = new BuriedEvent("push_delay");
        event.getVal_lab().put("pushts", Long.parseLong(msgpushts));
        event.getVal_lab().put("pushid", msgpushid);
        event.getVal_lab().put("recvts", Long.parseLong(localmills));
        event.getVal_lab().put("pushch", msgpushch);
        if (!TextUtils.isEmpty(orderts)) {
            event.getVal_lab().put("orderts", Long.parseLong(orderts));
        }
        if (TimeConstants.getInstance().getAppLaunchTS() != 0) {
            event.getVal_lab()
                    .put("launchts", TimeConstants.getInstance().getAppLaunchTS());
        }
        if (TimeConstants.getInstance().getDeviceOnTS() != 0) {
            event.getVal_lab().put("bootts", TimeConstants.getInstance().getDeviceOnTS());
        }
        boolean isVoiceOpen = Global.getPushVoiceState();
        event.getVal_lab().put("voice_open", isVoiceOpen ? "1" : "0");
        event.getVal_lab().put("media_volume", mStreamVolume);
        packet.getEvs().add(event);
        packet.setTm(System.currentTimeMillis());
        return packet;
    }

    private Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case UiMessageListener.INIT_ERROR:

                    break;

                case UiMessageListener.INIT_SUCCESS:
                    BaiduTts.getInstance().doneBaiduTtsDeferred();
                    break;

                case UiMessageListener.AUTHINFO_ERROR:

                    break;

                case UiMessageListener.AUTHINFO_SUCCESS:

                    break;

                case UiMessageListener.BAIDUTTS_ERROR:
                    BaiduTtsEvent baiduTtsEventE = (BaiduTtsEvent) msg.obj;
                    postTtsCode(baiduTtsEventE.getCode(), baiduTtsEventE.getUtteranceId());
                    break;

                case UiMessageListener.BAIDUTTS_SUCCESS:
                    BaiduTtsEvent baiduTtsEventS = (BaiduTtsEvent) msg.obj;
                    postTtsCode(baiduTtsEventS.getCode(), baiduTtsEventS.getUtteranceId());
                    break;

                default:
                    break;
            }
        }
    };

    /*--语音播报成功统计--*/
    private void postTtsCode(String code, String pushId) {
        MyApplication.getMyAppComponent()
                .retrofitMyApiHelper()
                .pushReportData(getTtsCodeEventObject(code, pushId))
                .subscribe(new RxObserver<Data>() {
                    @Override
                    public void onNext(Data data) {
                        super.onNext(data);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    private BuriedEventPacket getTtsCodeEventObject(String code, String pushId) {
        BuriedEventPacket packet = new BuriedEventPacket();
        BuriedEvent event = new BuriedEvent("order_bd_voice");
        event.getVal_lab().put("resultcode", code);
        event.getVal_lab().put("pushid", pushId);
        packet.getEvs().add(event);
        packet.setTm(System.currentTimeMillis());
        return packet;
    }

    public void speak(String msg, String pushId) {
        BaiduTts.getInstance().baiduTtsSpeak(msg, pushId);
    }

    @Override
    public void onDestroy() {
        BaiduTts.getInstance().release();
        super.onDestroy();
    }
}